// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-15

package remove

import (
	"context"
	"fmt"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib"
	"strings"
)

// Logic
// 删除分类.
type Logic struct {
	admin  *models.ArcadeAdmins
	arcade *models.Arcades

	affects     int64
	category    *models.GoodsCategory
	kind        kind.ArcadeAdminOperation
	kindContent string

	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// After
// 后置日志.
func (o *Logic) After(ctx context.Context, _ iris.Context, _ result.Result) {
	if o.affects > 0 {
		_, _ = services.NewArcadeLogsService().Add(ctx,
			o.arcade, o.admin, o.kind, o.kindContent,
		)
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Json(i, o.request); err == nil {
		o.arcade, o.admin = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)
	if err = db.Transaction(ctx,
		o.RunCheck,
		o.RunRemove,
	); err != nil {
		return res.WithError(err)
	}
	return res.With(o.response)
}

// RunCheck
// 查询数据.
func (o *Logic) RunCheck(ctx context.Context, sess *db.Session) (err error) {
	var has bool
	if o.category, has, err = services.NewGoodsCategoryService(sess).Dao.GetById(ctx, o.request.Id); err != nil {
		err = errs.ErrDatabaseQuery
	} else if !has || o.category.ArcadeId != o.arcade.Id {
		err = errs.ErrArcadePondNotFound
	}
	return
}

func (o *Logic) RunRemove(ctx context.Context, sess *db.Session) (err error) {
	if o.affects, err = services.NewGoodsCategoryService(sess).Dao.DeleteById(ctx, o.category.Id); err != nil {
		err = errs.ErrDatabaseQuery
	} else if o.affects > 0 {
		o.RunRemoveToLog()
	}
	return
}

func (o *Logic) RunRemoveToLog() {
	var changes = []string{
		fmt.Sprintf(`分类[%s]`, o.category.Name),
		fmt.Sprintf(`排序[%v]`, o.category.Sort),
	}

	o.kind = kind.ArcadeAdminOperationShopCategoryDelete
	o.kindContent = o.kind.ToShopCategoryDelete(strings.Join(changes, ", "))
}
